<?php
/*
 * 车型库级别管理
 * @package    auto
 * @author     yunian
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 6e90033a0d670cba9cdf8a805b3b22217a272254 $
 */
defined('IN_IXDCW') or exit('Access Denied');
$moduleid = isset($moduleid) ? intval($moduleid) : 29;
$typename = isset($typename) ? strval($typename) : '';
$typename or msg('请输入类型名称!');
$RANK     = PCache::read('autoCategory-' . $typename . '.php');
$MOD      = PCache::read('module-' . $moduleid . '.php');
$arid     = isset($arid) ? intval($arid) : 0;
$do       = new AutoCategoryModule($arid, $typename);
$parentid = isset($parentid) ? intval($parentid) : 0;
$table    = Table::name(Table::NAME_AUTO_CATEGORY);
$menus    = array(
	array('添加分类', '?file=' . $file . '&action=add&moduleid=' . $moduleid . '&parentid=' . $parentid . '&typename=' . $typename),
	array('管理分类', '?file=' . $file . '&moduleid=' . $moduleid . '&typename=' . $typename),
	array('批量索引', '?file=' . $file . '&action=letters&moduleid=' . $moduleid . '&typename=' . $typename),
	array('更新地址', '?file=' . $file . '&action=url&moduleid=' . $moduleid . '&typename=' . $typename),
	array('更新统计', '?file=' . $file . '&action=count&moduleid=' . $moduleid . '&typename=' . $typename),
	array('更新缓存', '?file=' . $file . '&action=cache&moduleid=' . $moduleid . '&typename=' . $typename),
	array('重名检测', '?file=' . $file . '&moduleid=' . $moduleid . '&action=repeat&typename=' . $typename),
);
switch ($action) {
	case 'add':
		// 如果是分级, 增加扩展字段的填充项
		if ($typename == AutoCategory::TYPE_RANK) {
			if (!isset($level)) $level = 0;
			if (!isset($parentid)) $parentid = 0;
			if ($parentid == 0) {
				$level = 0;
			} else {
				$parentInfo = $RANK[$parentid];
				if (isset($parentInfo['level'])) {
					$level = $parentInfo['level'] + 1;
				}
			}
			$extTable = AutoRank::tableByLevel($level);
			$FD       = AutoRank::fields($extTable);
		}
		if ($submit) {
			if (!$category['name']) msg('分级名不能为空');
			$category['name'] = trim($category['name']);
			$childs           = '';
			$arids            = array();
			if ($typename == AutoCategory::TYPE_RANK) {
				// 添加时候的图片处理
				if ($level == 0 || $level == 1) {
					$seType = 'brand_thumb';
				} elseif ($level == 2) {
					$seType = 'car_thumb';
				}
				if (isset($category[$seType])) {
					$seName = $moduleid .'_'. $seType;
					// 品牌缩略图
					if (empty($category[$seType])) {
						if (Session::get($seName)) {
							Picture::deleteAll(Session::get($seName));
							Session::del($seName);
						}
					} else {
						Session::del($seName);
					}
				}
				AutoField::update($post_fields, AutoRank::table($category), $arid, 'arid', $FD);
			}
			if (strpos($category['name'], "\n") === false) {
				$category['nickname'] = $do->getNickname($category['nickname']);
				$do->add($category);
				$childs .= ',' . $do->getArid();
				$arids[] = $do->getArid();
			} else {
				$categorys = explode("\n", $category['name']);
				foreach ($categorys as $name) {
					$name = trim($name);
					if (!$name) continue;
					$scategory             = array();
					$scategory['name']     = $name;
					$scategory['nickname'] = '';
					$scategory['letter']   = '';
					$scategory['parentid'] = $category['parentid'];
					$do->add($scategory);
					$childs .= ',' . $do->getArid();
					$arids[] = $do->getArid();
				}
			}
			if ($category['parentid']) {
				$parents   = array();
				$cid       = $category['parentid'];
				$parents[] = $cid;
				while (1) {
					if ($RANK[$cid]['parentid']) {
						$parents[] = $cid = $RANK[$cid]['parentid'];
					} else {
						break;
					}
				}
				foreach ($parents as $arid) {
					$arrchildid = $RANK[$arid]['child'] ? $RANK[$arid]['arrchildid'] . $childs : $arid . $childs;
					$db->query("UPDATE {$table} SET child=1,arrchildid='$arrchildid' WHERE arid=$arid");
				}
			}
			$do->cache();
			dmsg('添加成功', '?file=' . $file . '&moduleid=' . $moduleid . '&parentid=' . $category['parentid'] . '&typename=' . $typename);

		} else {
			include tpl('category_add', $module);
		}
		break;
	case 'edit':
		$arid or msg();
		if ($submit) {
			if (!$category['name']) msg('分类名不能为空');
			if ($category['parentid'] == $arid) msg('上级分类不能与当前分类相同');
			if ($typename == AutoCategory::TYPE_RANK) {
				// handler image
				$r = AutoRank::get($category['level'], $arid);
				if ($category['level'] == 0 || $category['level'] == 1) {
					$seType = 'brand_thumb';
				} elseif ($category['level'] == 2) {
					$seType = 'car_thumb';
				}
				$seName = $moduleid .'_'. $seType;
				ThumbUpload::clearPicture($seType, $post_fields[$seType], $r[$seType], $_userid);
				// update extend Data
				$extTable = AutoRank::table($category);
				$FD       = AutoRank::fields($extTable);
				AutoField::update($post_fields, AutoRank::table($category), $arid, 'arid', $FD);
			}
			// update main data
			$do->edit($category);
			$category['arid'] = $arid;
			$do->cache();
			dmsg('修改成功', '?file=' . $file . '&moduleid=' . $moduleid . '&parentid=' . $category['parentid'] . '&typename=' . $typename);
		} else {

			$categoryInfo = $db->getOne("SELECT * FROM {$table} WHERE arid=$arid");
			$extTable     = AutoRank::table($categoryInfo);
			if ($extTable) {
				$FD      = AutoRank::fields($extTable);
				$extInfo = $db->getOne("select * from {$extTable} where arid=$arid");
			}
			unset($categoryInfo['item']);
			extract($categoryInfo);
			include tpl('category_edit', $module);
		}
		break;
	case 'count':
		$tb = get_table($moduleid);
		if (!isset($num)) {
			$num = 50;
		}
		if (!isset($fid)) {
			$r   = $db->getOne("SELECT MIN(arid) AS fid FROM {$table} WHERE moduleid=$moduleid");
			$fid = $r['fid'] ? $r['fid'] : 0;
		}
		isset($sid) or $sid = $fid;
		if (!isset($tid)) {
			$r   = $db->getOne("SELECT MAX(arid) AS tid FROM {$table} WHERE moduleid=$moduleid");
			$tid = $r['tid'] ? $r['tid'] : 0;
		}
		if ($fid <= $tid) {
			$result = $db->query("SELECT arid FROM {$table} WHERE moduleid=$moduleid AND arid>=$fid ORDER BY arid LIMIT 0,$num");
			if ($db->affectedRows($result)) {
				while ($r = $db->fetchArray($result)) {
					$arid = $r['arid'];
					if ($moduleid == 4) {
						$condition = "groupid>5 and catids like '%," . $arid . ",%'";
					} else {
						$condition = 'status=3';
						$condition .= $CATEGORY[$arid]['child'] ? " AND arid IN (" . $CATEGORY[$arid]['arrchildid'] . ")" : " AND arid=$arid";
					}
					$item = $db->count($tb, $condition);
					$db->query("UPDATE {$table} SET item=$item WHERE arid=$arid");
				}
				$arid += 1;
			} else {
				$arid = $fid + $num;
			}
		} else {
			$do->cache();
			dmsg('更新成功', "?moduleid=$moduleid&file=$file" . '&typename=' . $typename);
		}
		msg('ID从' . $fid . '至' . ($arid - 1) . '更新成功' . progress($sid, $fid, $tid), "?moduleid=$moduleid&file=$file&action=$action&sid=$sid&fid=$arid&tid=$tid&num=$num");
		break;
	case 'cknickname':
		if ($do->getNickname($nickname)) {
			dialog('目录名可以使用');
		} else {
			dialog('目录名不合法或者已经被使用');
		}
		break;
	case 'cache':
		$do->repair();
		dmsg('更新成功', "?moduleid=$moduleid&file=$file&typename=$typename");
		break;
	case 'delete':
		if ($arid) $arids = $arid;
		$arids or msg();
		$do->delete($arids);
		$do->repair();
		dmsg('删除成功', $forward);
		break;
	case 'update':
		if (!$category || !is_array($category)) msg();
		$do->update($category, $arids);
		$do->repair();
		dmsg('更新成功', $forward);
		break;
	case 'letters':
		$update = false;
		foreach ($CATEGORY as $k => $v) {
			if (strlen($v['letter']) != 1) {
				$letter = Str::text2py($catname, 1);
				if ($letter) {
					$update = true;
					$letter = substr($letter, 0, 1);
					$db->query("UPDATE {$table} SET letter='$letter' WHERE arid='$v[arid]'");
				}
			}
		}
		if ($update) $do->repair();
		dmsg('建立成功', $forward);
		break;
	case 'letter':
		isset($catname) or $catname = '';
		if (!$catname || strpos($catname, "\n") !== false) exit('');
		if (strtoupper(DT_CHARSET) != 'UTF-8') $catname = Str::convert($catname, 'UTF-8', DT_CHARSET);
		exit(Str::text2py($catname, 1));
		break;
	case 'repeat':
		$num   = isset($num) ? intval($num) : 100;
		$lists = array();
		if ($submit) {
			$condition = ' where 1 ';
			if ($keyword) $condition .= " AND `$key` LIKE '%$keyword%'";
			if ($typename) $condition .= " and typename ='$typename'";
			$result = $db->query("SELECT COUNT(`$key`) AS num,`$key` FROM $table $condition GROUP BY `$key` ORDER BY num DESC LIMIT 0,$num");
			while ($r = $db->fetchArray($result)) {
				if ($r['num'] < 2) continue;
				$lists[] = $r;
			}
		}
		include tpl($action, $module);
		break;
	case 'search':
		$total  = 0;
		$XDRANK = array();
		$sql    = "SELECT * FROM {$table} WHERE parentid=$parentid and typename='{$typename}' ORDER BY listorder,letter";
		$result = $db->query($sql);
		while ($r = $db->fetchArray($result)) {
			$r['childs'] = substr_count($r['arrchildid'], ',');
			$total += $r['item'];
			$XDRANK[$r['arid']] = $r;
		}
		include tpl('category', $module);
		break;
	default:
		$total  = 0;
		$XDRANK = array();
		$sql    = "SELECT * FROM {$table} WHERE parentid=$parentid and typename='{$typename}' ORDER BY letter, listorder";
		$result = $db->query($sql);
		while ($r = $db->fetchArray($result)) {
			$r['childs'] = substr_count($r['arrchildid'], ',');
			$total += $r['item'];
			$XDRANK[$r['arid']] = $r;
		}
		if (!$XDRANK && !$parentid) msg('暂无分级,请先添加', '?file=' . $file . '&moduleid=' . $moduleid . '&action=add&parentid=' . $parentid . '&typename=' . $typename);
		include tpl('category', $module);
		break;
}
